import { create } from 'zustand'
import { ThemeMode } from '@/config/theme'

interface ThemeStore {
  theme: ThemeMode
  toggleTheme: () => void
  setTheme: (theme: ThemeMode, skipIpc?: boolean) => void
}

const getInitialTheme = (): ThemeMode => {
  const saved = localStorage.getItem('theme-mode')
  return saved === 'light' || saved === 'dark' ? saved : 'dark'
}

export const useThemeStore = create<ThemeStore>(set => ({
  theme: getInitialTheme(),

  setTheme: (newTheme, skipIpc = false) => {
    set({ theme: newTheme })
    localStorage.setItem('theme-mode', newTheme)
    if (!skipIpc && window.ipcRenderer) {
      window.ipcRenderer.send('theme-changed', newTheme)
    }
  },

  toggleTheme: () => {
    set(state => {
      const newTheme = state.theme === 'dark' ? 'light' : 'dark'
      localStorage.setItem('theme-mode', newTheme)
      if (window.ipcRenderer) {
        window.ipcRenderer.send('theme-changed', newTheme)
      }
      return { theme: newTheme }
    })
  },
}))
